package m202406.d09;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/9 12:30
 */
public class Q18 {

    public static void main(String[] args) {
        Q18 q18 = new Q18();
        q18.fourSum(new int[]{1,-2,-5,-4,-3,3,3,5}, -11);
    }

    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int first = 0; first < nums.length; first++) {
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            for (int second = first + 1; second < nums.length; second++) {
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                for (int third = second + 1, forth = nums.length - 1; third < forth; ) {
                    if (third > second + 1 && nums[third] == nums[third - 1]) {
                        third++;
                        continue;
                    }
                    long temp = (long) nums[first] + nums[second] + nums[third] + nums[forth];
                    if (temp < target) {
                        third++;
                    } else if (temp > target) {
                        forth--;
                    } else {
                        res.add(List.of(nums[first], nums[second], nums[third], nums[forth]));
                        third++;
                    }
                }

            }
        }
        return res;
    }
}
